package com.digitalchina.lxnsy.activity.management;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.LandVO;
import com.digitalchina.lxnsy.entity.SeedVO;
import com.digitalchina.lxnsy.toolkit.CustomDialog;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.lzy.okhttputils.model.HttpParams;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity.management
 * 创建人：郑皓
 * 创建时间：2019/4/25 16:58
 * 修改备注：
 * ================================================
 */
public class GrowSeedActivity extends BaseActivity {

    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_land)
    TextView tvLand;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_variety)
    TextView tvVariety;
    @Bind(R.id.et_num_bags)
    EditText etNumBags;
    @Bind(R.id.et_num_hole)
    EditText etNumHole;
    @Bind(R.id.et_num_grow)
    EditText etNumGrow;
    @Bind(R.id.et_num_people)
    EditText etNumPeople;
    @Bind(R.id.et_work_time)
    EditText etWorkTime;
    @Bind(R.id.tv_grow_time)
    TextView tvGrowTime;
    @Bind(R.id.et_member)
    EditText etMember;

    private OptionsPickerView pvName, pvVariety, pvLand;
    private DatePickerDialog pvDate, dateGrowTime;

    private int mYear;
    private int mMonth;
    private int mDayOfMonth;

    private String cropId = ""; // 农作物ID
    private String varietyId = ""; // 品种ID
    private String landParcelInfoId = ""; // 地块ID

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_grow_seed);
        setTitle("育苗");
    }

    @Override
    public void initMember() {

        getSeedList();
        getLandList();

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        pvDate = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                tvDate.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
            }
        }, mYear, mMonth, mDayOfMonth);

        dateGrowTime = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                tvGrowTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
            }
        }, mYear, mMonth, mDayOfMonth);

    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case MSG_S_0: // 保存
                        CustomDialog.nativeDialogFinish(activity, "保存成功");
                        break;
                    case MSG_F_0:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_1: // 农作物
                        callBack(message.obj);
                        break;
                    case MSG_S_2: // 地块
                        setLand(message.obj);
                        break;
                }
                return false;
            }
        });
    }

    private void setLand(Object obj) {

        final List<LandVO> landList = FastJsonUtil.getListBean(obj.toString(), "landParcelInfoVOList", LandVO.class);


        pvLand = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                tvLand.setText(landList.get(options1).getPickerViewText());
                landParcelInfoId = landList.get(options1).getLandParcelId();
            }
        })
                .setTitleText("地块")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvLand.setPicker(landList);

    }

    @Override
    public void callBack(Object object) {
        final List<SeedVO> voList = FastJsonUtil.getListBean(object.toString(), "list", SeedVO.class);
        final List<SeedVO> varietyList = new ArrayList<>();

        // 设置分类
        pvName = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (voList == null || voList.size() == 0){
                    showToast("正在获取作物，请稍候重试");
                    return;
                }

                tvName.setText(voList.get(options1).getPickerViewText());
                tvVariety.setText("");
                cropId = voList.get(options1).getId();
                varietyId = "";
                varietyList.clear();
                for (int i = 0; i < voList.get(options1).getVariety().size(); i++) {
                    varietyList.add(voList.get(options1).getVariety().get(i));
                }
                pvVariety.setPicker(varietyList);
            }
        })
                .setTitleText("作物")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvName.setPicker(voList);

        pvVariety = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                tvVariety.setText(varietyList.get(options1).getPickerViewText());
                varietyId = varietyList.get(options1).getId();
            }
        })
                .setTitleText("品种")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvVariety.setPicker(varietyList);
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_date, R.id.layout_name, R.id.layout_variety, R.id.layout_land, R.id.layout_grow_time, R.id.bt_save})
    public void onViewClicked(View view) {
        hideKeyboard();
        switch (view.getId()) {
            case R.id.layout_date:
                pvDate.show();
                break;
            case R.id.layout_name:
                if (pvName != null)
                    pvName.show();
                else {
                    showToast("正在获取作物");
                }
                break;
            case R.id.layout_variety:
                if (pvVariety != null) {
                    if (StringUtil.isTextEmpty(tvName)) {
                        showToast("请先选择作物");
                    } else
                        pvVariety.show();
                } else {
                    showToast("正在获取品种");
                }
                break;
            case R.id.layout_land:
                if (pvLand != null)
                    pvLand.show();
                else {
                    showToast("正在获取地块");
                }
                break;
            case R.id.layout_grow_time: // 出苗时间
                dateGrowTime.show();
                break;
            case R.id.bt_save:
                save();
                break;
        }
    }

    private void save() {

        if (StringUtil.isTextEmpty(tvDate)) {
            showToast("请选择日期");
            return;
        }

        if (StringUtil.isTextEmpty(tvLand)) {
            showToast("请选择地块");
            return;
        }

        if (StringUtil.isTextEmpty(tvName)) {
            showToast("请选择作物");
            return;
        }

        if (StringUtil.isTextEmpty(tvVariety)) {
            showToast("请选择品种");
            return;
        }

        if (StringUtil.isTextEmpty(etNumBags)) {
            showToast("请填写袋数");
            return;
        }

        if (StringUtil.isTextEmpty(etNumHole)) {
            showToast("请填写穴盘");
            return;
        }

        if (StringUtil.isTextEmpty(etNumGrow)) {
            showToast("请填写育苗数");
            return;
        }

        if (StringUtil.isTextEmpty(etNumPeople)) {
            showToast("请填写人数");
            return;
        }

        if (StringUtil.isTextEmpty(etWorkTime)) {
            showToast("请填写工时");
            return;
        }

        if (StringUtil.isTextEmpty(tvGrowTime)) {
            showToast("请选择出苗时间");
            return;
        }

        if (StringUtil.isTextEmpty(etMember)) {
            showToast("请填写社员");
            return;
        }


        /**
         * resNo	资源编号
         * enterpriseId	企业ID
         * operationDate	日期
         * cropId	农作物ID
         * bagNumber	袋数
         * varietyId	品种ID
         * acupointPlate	穴盘（个）
         * seedlingNumber	育苗数量
         * peopleNumber	人数
         * hours	工时
         * emergenceDate	出苗日期
         * member	社员
         * landParcelInfoId	地块ID
         */
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("userAccId", AdminXML.getUserAccId(activity));
        params.put("operationDate", tvDate.getText().toString());
        params.put("landParcelInfoId", landParcelInfoId);
        params.put("cropId", cropId);
        params.put("varietyId", varietyId);
        params.put("bagNumber", etNumBags.getText().toString());
        params.put("acupointPlate", etNumHole.getText().toString());

        params.put("seedlingNumber", etNumGrow.getText().toString());
        params.put("peopleNumber", etNumPeople.getText().toString());
        params.put("hours", etWorkTime.getText().toString());
        params.put("emergenceDate", tvGrowTime.getText().toString());
        params.put("member", etMember.getText().toString());

        OkHttpUtil.post(activity, URL.URL_SAVE_SEEDLING, "正在保存", params, mHandler,
                MSG_S_0, MSG_F_0);

    }

    // 获取农作物品种 0不带品种  1带品种
    private void getSeedList() {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("type", "1");

        OkHttpUtil.post(activity, URL.URL_GET_SEED_LIST, "", params, mHandler,
                MSG_S_1, MSG_F_1);
    }
    // 获取地块
    private void getLandList() {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));

        OkHttpUtil.post(activity, URL.URL_GET_LAND_LIST, "", params, mHandler,
                MSG_S_2, MSG_F_2);
    }
}
